<?php
/**
 * 景彤供应商SDK
 * @author 陈韵
 */
namespace App\Service\VendorClient\Shopjingtong;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use App\Model\PssModel\ServiceConfig;

class ShopjingtongApiClient
{
    private $account  = 'Shopjingtong';
    protected $config;
    protected $RouteMap = [
        'queryGoodsList'        => '/externalApi/sku/queryCustSkuList',
       // 'queryGoodsDetail'      => '/externalApi/sku/querySkuById',
        'createOrder'           => '/externalApi/order/createOrder',
        //'batchSkuInfo'          => '/externalApi/sku/batchSkuInfo',
    ];
    

    public function __construct($apiBody = []){
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
/**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo1");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        $orderItemList    = [];
        $productAmt  = $TaxAmt = 0 ;

        //获取下单商品信息
        foreach ($params['orderGoods'] as $key => $item )
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;
            //如果商品除不尽，得多取以为，减去实际金额为折扣，折扣不能为负数
            if( $key == 0 ) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money,(string)$quantity,3);
                $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney,(string)100,1);
                $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100,2);
                $price               = bcadd((string)$price, (string)$singleDeliveryMoney,2);
            }
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            $singleGoodsPrice   = bcdiv((string)$singleGoodsPrice,'100',2);
            $totalGoods         = bcmul((string)$singleGoodsPrice,(string)$buyAcount,2);

            //含税税率
            $tax_rate           = bcadd('1', (string)$item['tax_rate'],4);
            
            //不含税价格
            $not_tax_price      = bcdiv((string)$singleGoodsPrice, (string)$tax_rate,3);
            // echo "含税税率:".$tax_rate."不含税价格：".$not_tax_price;
            $not_tax_price      = ceil(bcmul((string)$not_tax_price,(string)'100',1));
            // echo "含税税率:".$tax_rate."不含税价格：".$not_tax_price;
            $not_tax_price      = bcdiv((string)$not_tax_price,'100',2);
            
            //税金
            $singleGoodsTax     = bcsub((string)$singleGoodsPrice, (string)$not_tax_price,3);
            
            //单个商品总税金
            $totalGoodsTax      = bcmul((string)$singleGoodsTax,(string)$buyAcount,2);
            
            //单个商品总不含税价格
            $notTotalGoods      = bcmul((string)$not_tax_price,(string)$buyAcount,2);
            
            $orderItemList[]= [
                'consumptionTax'        => 0,
                'customsTax'            => 0,
                'dutiablePrice'         => (int)bcmul($notTotalGoods,'100',2),
                'extItemId'             => (string)$item['supplier_skucode'],
                'firstQuantity'         => 1,
                'itemPrice'             => (int)bcmul($not_tax_price,'100',2),
                'itemTotalActualPrice'  => (int)bcmul($notTotalGoods,'100',2),
                'itemTotalPrice'        => (int)bcmul($notTotalGoods,'100',2),
                'quantity'              => (string)$buyAcount,
                'totalTax'              => (int)bcmul($totalGoodsTax,'100',2),
                'vat'                   => (int)bcmul($totalGoodsTax,'100',2),
            ];
            $productAmt = bcadd((string)$productAmt,(string)$notTotalGoods,2);
            $TaxAmt = bcadd((string)$TaxAmt,(string)$totalGoodsTax,2);
        }

        //实际下单金额
        $real_total_money = $orderInfo['real_total_money'];
        //订单总金额 = 含税商品总金额 + 运费 - 优惠金额
        $ActualPaidAmt = bcadd((string)$productAmt,(string)$TaxAmt,2);
        //优惠金额
        $discount_money = bcsub((string)$ActualPaidAmt,$real_total_money,2);
        
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        //支付拓展信息
        $apply_extends      = @json_decode($orderInfo['apply_extends'],true);
        $apply_extends      = empty($apply_extends) ? $order : $apply_extends;
        
        //支付时间
        $payTime        = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        //支付时间
        $pay_time       = $payTime ? $payTime : time();
        $pay_time       = date('c',$pay_time);
        
        //支付流水号
        $pay_sn         = $order['paySerial']??$orderInfo['pay_sn'];
        
        //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $payCommanyName = $apply_extends['payCommanyName'] ?? '';
        $payCommanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        $payCommanyName = $order['payCommanyName'] ? $order['payCommanyName'] : $payCommanyName;
        
        $pay_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_PAY, $payCommanyCode);
        if (empty($pay_value)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$payCommanyCode}】未映射，请联系管理员处理");
        }

        //电商平台信息
        $enterpriseNum = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;
        if(empty($enterpriseNum) or empty($enterpriseName)){
            return Normal::returnCode(Normal::FAIL, "电商平台信息不能为空");
        }
        //获取身份证正反面
        $IdCardFrontImage = $apply_extends['idCardFrontImage'] ?? '';
        $IdCardBackImage  = $apply_extends['idCardBackImage'] ?? '';
        $IdCardFrontImage = $order['idCardFrontImage'] ? $order['idCardFrontImage'] : $IdCardFrontImage;
        $IdCardBackImage  = $order['idCardBackImage'] ? $order['idCardBackImage'] : $IdCardBackImage;

        //客户信息
        $customsDeclareInfo = [
            'buyerIdCardBackPic'    => $IdCardBackImage ? $IdCardBackImage : "pic",
            'buyerIdCardFrontPic'   => $IdCardFrontImage ? $IdCardBackImage : "pic",
            'buyerIdCardPicType'    => "1",
            'buyerIdNo'             => $orderInfo["buyer_idcard"],
            'buyerIdType'           => "1",
            'buyerName'             => $orderInfo["buyer_realname"],
            'contactNo'             => (int)$orderInfo["buyer_phone"],
            'gender'                => "男",
            'nationality'           => "CN",
            'payOrderId'            => $pay_sn,
        ];
        
        //订单信息
        $order = [
            'custCode'              => $this->config['custCode'],
            'externalOrderCode'     => $orderInfo['supplier_dsn'],
            'orderCreateTime'       => date("c"),
            'orderPayTime'          => $pay_time,
            'platformFlag'          => 2,
            'customRecord'          => $enterpriseName,
            'customCode'            => $enterpriseNum,
            'defaultFlag'           => 0,
            'payChannel'            => $pay_value,
            'payCompany'            => $payCommanyName,
            'payCompanyCode'        => $payCommanyCode,
        ];

        //订单订单总价信息
        $orderAmountInfo = [
            'actualPayment'         => (int)bcmul($orderInfo["real_total_money"],'100',2),
            'consumptionTax'        => 0.00,
            'coupon'                => (int)bcmul($discount_money,'100',2),
            'customsTax'            => 0.00,
            'dutiablePrice'         => (int)bcmul($productAmt,'100',2),
            'insurance'             => 0.00,
            'postFee'               => 0.00,
            'totalTax'              => (int)bcmul($TaxAmt,'100',2),
            'vat'                   => (int)bcmul($TaxAmt,'100',2),
        ];
        
        //订单联系人信息
        $orderContactPeople = [
            'address'               => $orderInfo["receive_address"],
            'city'                  => $orderInfo['city'],
            'contactNo'             => (int)$orderInfo['recveive_phone'],
            'country'               => "CN",
            'district'              => $orderInfo['district'],
            'name'                  => $orderInfo["receive_name"],
            'province'              => $orderInfo['province'],
        ];
        
        //创建订单数据
        $data = [
            'customsDeclareInfo'    => $customsDeclareInfo,
            'order'                 => $order,
            'orderAmountInfo'       => $orderAmountInfo,
            'orderContactPeople'    => $orderContactPeople,
            'orderItemList'         => $orderItemList,
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data,
        ];
        $res  = $this->execute($requestParam);
        return $res;
    }
  
    /**
     * 查询商品信息
     */
    public function queryGoodsList($param)
    {
        //获取商品列表
        $goodsWhere = [
            'custCode'  => $this->config["custCode"],
            'pageSize'  => $param['limit']  ?? 100,
            'pageNum'   => $param['page']  ? (int)bcsub($param['page'], 1) : 0,
        ];
        $requestParam = [
            'method'    => 'queryGoodsList',
            'data'      => $goodsWhere,
        ];
        $res  = $this->execute($requestParam);
        if($res["code"] != Normal::SUC or !isset($res["data"]["skuList"]) or empty($res["data"]["skuList"])){
            return $res;
        }
        $details = $res["data"]["skuList"];
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'data'      => $details,
            'has_next'  => true
        ]);
        
    }
   
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] ){
        
        $method = $param["method"];
        $url    = $this->config["baseurl"].$this->RouteMap[$method];
        if($method == "queryGoodsList"){
            $parameter = [
                [
                    'tag'    => 'Shopjingtong_' . $method,
                    'uid'    => IdService::instance()->getOtherID(),
                    'url'    => $url,
                    'data'   => $param['data'],
                    'method' => "post",
                    'format' => '',
                    'header' => []
                ]
            ];
        }else{
            $parameter = [
                [
                    'tag'    => 'Shopjingtong_' . $method,
                    'uid'    => IdService::instance()->getOtherID(),
                    'url'    => $url,
                    'data'   => $param['data'],
                    'method' => "post",
                    'format' => 'json',
                    'header' => []
                ]
            ];
        }
        if( in_array($method,['queryGoodsList']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask   = current($resTask);
        $response  = $resTask['response']['result'];
        $result    = @json_decode($response, true);
        if (isset($result['success']) && $result['success'] == true) {
            return Normal::returnCode(Normal::SUC, "OK",$result);
        }
        $message = $result['errorMsg'] ?? '操作失败';
        return Normal::returnCode(Normal::FAIL, $message);
        
    }
  
}